import { defineStore } from "pinia";
import CryptoJS from 'crypto-js'
const pwd = 'qwerty'

export const useUser = defineStore('user', {
    state() {
        return {
            user: {},
            userInfo: {
                id: '',
                name: '',
                loginName: '',
                departmentId: '',
                roles: [],
                token: ''
            }
        }
    },
    actions: {
        // 替换整个用户对象（保持向后兼容）
        replace(value) {
            this.user = value
        },
        
        // 设置用户信息
        setUserInfo(userInfo) {
            this.userInfo = {
                ...this.userInfo,
                ...userInfo
            }
        },
        
        // 设置用户基本信息
        setBasicInfo(basicInfo) {
            this.userInfo = {
                ...this.userInfo,
                id: basicInfo.id || '',
                name: basicInfo.name || '',
                loginName: basicInfo.loginName || '',
                departmentId: basicInfo.departmentId || '',
                roles: basicInfo.roles || []
            }
        },
        
        // 设置token
        setToken(token) {
            this.userInfo.token = token
        },
        
        // 清除用户信息
        clear() {
            this.user = {}
            this.userInfo = {
                id: '',
                name: '',
                loginName: '',
                departmentId: '',
                roles: [],
                token: ''
            }
        }
    },
    getters: {
        // 获取用户对象（保持向后兼容）
        getUser() {
            return this.user
        },
        
        // 获取用户信息
        getUserInfo() {
            return this.userInfo
        },
        
        // 获取用户ID
        getUserId() {
            return this.userInfo.id
        },
        
        // 获取用户名
        getUserName() {
            return this.userInfo.name
        },
        
        // 获取登录名
        getLoginName() {
            return this.userInfo.loginName
        },
        
        // 获取部门ID
        getDepartmentId() {
            return this.userInfo.departmentId
        },
        
        // 获取用户角色
        getUserRoles() {
            return this.userInfo.roles
        },
        
        // 获取token
        getToken() {
            return this.userInfo.token
        },
        
        // 检查是否已登录
        isLoggedIn() {
            return !!this.userInfo.token
        }
    },
    persist: {
        storage: localStorage,
        // serializer: {
        //     serialize: (state) => CryptoJS.AES.encrypt(state, pwd).toString() ,
        //     deserialize: (data) => CryptoJS.AES.decrypt(data, pwd).toString(),
        //   },
    }
}) 